﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using PokeIn.Comet;
using PokeIn;
using NotifyServiceReference;

/// <summary>
/// using to check and update real time of client
/// </summary>
public class NotifyToClient
{
    // internal Thread to send message to client
    private Thread internalThread = null;

	public NotifyToClient()
	{
        AppDomain.CurrentDomain.DomainUnload += new EventHandler(CurrentDomain_DomainUnload);
	}

    public void Start()
    {
        if (internalThread == null)
        {
            internalThread = new Thread(CheckNewMessage);
            internalThread.Start();
        }
    }

    private void CurrentDomain_DomainUnload(object sender, EventArgs e)
    {
        if (internalThread != null)
        {
            try
            {
                internalThread.Abort();
            }
            catch
            {
            }
        }
    }

    private void CheckNewMessage()
    {
        int i = 0;
        while (true)
        {
            NotifyServiceClient nsc = new NotifyServiceClient();
            String[] clientIds = CometWorker.GetClientIds();
            foreach (String clientId in clientIds)
            {
                object obj;
                CometWorker.GetClientObject(clientId, "MyClients", out obj);
                // if client is online => obj != null
                if (obj != null)
                {
                    MyClients client = (MyClients)obj;
                    int count = nsc.CountNewMessage(client.ClientId);
                    // if client change new message
                    if (count != client.NotifyCount)
                    {
                        // send message to client
                        client.NotifyCount = count;
                        CometWorker.SendToClient( clientId, JSON.Method("CheckNewMessage", "" + count));
                    }
                }
            }
            i++;
            Thread.Sleep(1000);
        }
    }
}